#!/bin/bash
root_dir="/usr/local/edh"
script_path=$(readlink -f "${BASH_SOURCE[0]}")
script_dir=$(dirname "$script_path")
if [ ! -d "$root_dir" ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING $root_dir undetected"
  mkdir -p $root_dir
  if [ $? -eq 0 ];then
    echo "$(date +"%Y-%m-%d %H:%M:%S") INFO creating $root_dir success"
  else
    echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR creating $root_dir fail"
    return
  fi
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO $root_dir detected"
fi

MODE_FILE="$script_dir/mode"
if [[ ! -e "$MODE_FILE" ]];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR flink mode is empty"
  return
fi

jdk_ver=$(java -version 2>&1)
if [[ $jdk_ver == *"not found"* ]];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING jdk is not found,please install jdk first"
  return
else
  echo $jdk_ver
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO jdk detected"
fi


if [ ! -d "$root_dir/flink" ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO $root_dir/flink undetected"
  tar -zxvf flink-2.0.0-bin-scala_2.12.tgz  -C "$root_dir"
  if [ $? -eq 0 ];then
    echo "$(date +"%Y-%m-%d %H:%M:%S") INFO unzip $script_dir/flink-2.0.0-bin-scala_2.12.tgz success"
  else
    echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR unzip $script_dir/flink-2.0.0-bin-scala_2.12.tgz fail"
    return
  fi
  mv "$root_dir/flink-2.0.0" "$root_dir/flink"
  rm $root_dir/flink/conf/config.yaml
  rm $root_dir/flink/conf/masters
  rm $root_dir/flink/conf/workers
  env_file="$script_dir/config.env"
  conf_dir=$root_dir/flink/conf
  while IFS= read -r line
  do
  	if [[ -n "$line" ]];then
      IFS="_" read -r prefix suffix <<< "$line"
  	  IFS="=" read -r name value <<< "$suffix"
      echo "$(date +"%Y-%m-%d %H:%M:%S") setting $name=$value"
      if [ $prefix == "CONF" ];then
        echo "$name: $value" >> $conf_dir/config.yaml
      fi
      if [ $prefix == "MASTER" ];then
        echo -e "$value" >> $conf_dir/masters
      fi
      if [ $prefix == "WORKER" ];then
        echo -e "$value" >> $conf_dir/workers
      fi
  	fi
  done < "$env_file"
  echo "export FLINK_HOME=$root_dir/flink" >> ~/.bashrc
  echo 'export PATH=$FLINK_HOME/bin:$PATH' >> ~/.bashrc
  echo "export FLINK_HOME=$root_dir/flink" >> /etc/profile
  echo 'export PATH=$FLINK_HOME/bin:$PATH' >> /etc/profile
  source ~/.bashrc
  source /etc/profile
  flink -v
else
  source ~/.bashrc
  source /etc/profile
  flink -v
fi
